#include "http.h"
#include "ui_http.h"
#include <QDebug>
#include <QFile>
#include <QHostAddress>
#include "index.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QString>
http::http(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::http)
{
    ui->setupUi(this);

}

http::~http()
{
    delete ui;
}

void http::start(){
    first();
}

void http::first(){
    server = new QTcpServer(this);

    if(!server->listen(QHostAddress::LocalHost, 8080))
    {
        qDebug() << "Web服务未启动";
    }
    else
    {
        qDebug() << "Web服务在端口8080等待客户端连接";
    }
    //有客户端连接时触发newConnection信号
    connect(server, &QTcpServer::newConnection, this, &http::connection);
}

void http::on_pushButton_clicked(bool checked)
{
    server = new QTcpServer(this);

    if(!server->listen(QHostAddress::Any, 8080))
    {
        qDebug() << "Web服务未启动";
    }
    else
    {
        qDebug() << "Web服务在端口8080等待客户端连接";
    }
    //有客户端连接时触发newConnection信号
    connect(server, &QTcpServer::newConnection, this, &http::connection);
}



void http::connection()
{
    //取出建立好连接的套接字
    QTcpSocket *socket = server->nextPendingConnection();

    //获取对方的IP和端口
    QHostAddress clientIp = socket->peerAddress();//客户端的IP
    qint16 port = socket->peerPort();//客户端的端口

    //QByteArray array = socket->readAll();
    //qDebug()<<(socket->readAll());

    if(tcpSktList.contains(socket))
    {
        qDebug()<<QString("%1:%2的连接早已建立过").arg(clientIp.toString()).arg(port);
    }
    else
    {
        qDebug()<<QString("新的连接已建立 %1:%2").arg(clientIp.toString()).arg(port);
        tcpSktList.append(socket);//记录下客户端发起的连接
        connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));//客户端掉线处理
        connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));//客户端发来的数据处理
        //connect(socket, SIGNAL(readyRead()), this, SLOT(sec()));//客户端发来的数据处理
    }
}

void http::onReadyRead()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
    QJsonObject json;
    if(socket)
    {
        //从通信套接字中取出内容
        QByteArray array = socket->readAll();
        qDebug()<<(socket->readAll());
        QString request = QString::fromUtf8(array);
        qDebug() << "正在从浏览器读取数据= " << request;//打印收到的来自客户端的消息
        qDebug() << "sec " << request.indexOf("/sec");
        if(request.startsWith("GET"))//如果是GET请求
        {
            // QFile file("/Users/Administrator/Documents/http_demo/index.txt");
            if(request.indexOf("/sec")>0){
                QSqlQuery query("SELECT * FROM dbo.lpxx;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    int ID = query.value(0).toInt();
                    QString LoginName = query.value(1).toString();
                    QString LoginTime = query.value(2).toString();
                    QString LogoutTime = query.value(3).toString();
                    int OPeration = query.value(4).toInt();

                    json.insert("id",query.value(1).toString());
                    json.insert("name",query.value(2).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                char *ch = jsonString.toLocal8Bit().data();
                socket->write("HTTP/1.1 200 OK\r\n");
                socket->write("Content-Type: text/html\r\n");
                socket->write("\r\n");
                socket->write(ch);
                socket->flush();
                if(!socket->waitForBytesWritten(3000)){
                    socket->close();
                }
            }else
            {
                QFile file("O:/QT File/database/uiui/select.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串
                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                   // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket->write("HTTP/1.1 200 OK\r\n");
                socket->write("Content-Type: text/html\r\n");
                socket->write("\r\n");
                socket->write(ch);
                socket->flush();
                if(!socket->waitForBytesWritten(3000)){
                    socket->close();
                }
            }
        }
    }
    if(socket)
    {
        //从通信套接字中取出内容
        QByteArray array = socket->readAll();
        qDebug()<<(socket->readAll());
        QString request = QString::fromUtf8(array);
        qDebug() << "正在从浏览器读取数据= " << request;//打印收到的来自客户端的消息

        if(request.startsWith("POST"))//如果是GET请求
        {
            // QFile file("/Users/Administrator/Documents/http_demo/index.txt");

            /* QFile file("O:/QT File/database/index.html");
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                qDebug() << "文件打开失败";
                return;
            }
            QString tempStr = "";//临时字符串
            while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
            {
                //tempStr = file.readLine();  //读取文件中一行
                tempStr = file.readAll();   //读取文件中所有内容
                qDebug() <<"tempStr = "<<tempStr;
            }*/
            json.insert("id","success");
            QJsonDocument doc(json);
            QString jsonString = doc.toJson();
            char *ch = jsonString.toLocal8Bit().data();
            //sec();
            //char *ch = tempStr.toLatin1().data();
            // char *ch = tempStr.toLocal8Bit().data();
            socket->write("HTTP/1.1 200 OK\r\n");
            socket->write("Content-Type: text/html\r\n");
            socket->write("\r\n");
            socket->write(ch);
            socket->flush();


        }
    }
}

void http::onDisconnected()
{
    QTcpSocket *socket = static_cast<QTcpSocket *>(sender());
    //获取对方的IP和端口
    QHostAddress clientIp = socket->peerAddress();//客户端的IP
    qint16 port = socket->peerPort();//客户端的端口
    qDebug()<<QString("客户端掉线 %1:%2").arg(clientIp.toString()).arg(port);

    tcpSktList.removeOne(socket);
}

void http::sec()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());

    if(socket)
    {
        //从通信套接字中取出内容
        QByteArray array = socket->readAll();
        qDebug()<<(socket->readAll());
        QString request = QString::fromUtf8(array);
        qDebug() << "正在从浏览器读取数据= " << request;//打印收到的来自客户端的消息

        if(request.startsWith("GET"))//如果是GET请求
        {

            QSqlQuery query("SELECT * FROM dbo.lpxx;");
            //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
            QJsonArray root;
            QJsonObject json;
            int i=0;
            while (query.next())
            {
                int ID = query.value(0).toInt();
                QString LoginName = query.value(1).toString();
                QString LoginTime = query.value(2).toString();
                QString LogoutTime = query.value(3).toString();
                int OPeration = query.value(4).toInt();

                json.insert("id",query.value(1).toString());
                json.insert("name",query.value(2).toString());
                root.append(json);
                i++;
                //qDebug()<<root;

            }

            QJsonDocument doc(root);
            QString jsonString = doc.toJson();
            char *ch = jsonString.toLocal8Bit().data();
            socket->write("HTTP/1.1 200 OK\r\n");
            socket->write("Content-Type: text/html\r\n");
            socket->write("\r\n");
            socket->write(ch);
            socket->flush();
            if(!socket->waitForBytesWritten(3000)){
                socket->close();
            }

            //socket->waitForReadyRead(300);
        }
    }



    //QTcpSocket* socket = static_cast<QTcpSocket*>(sender());

}


